package com.example.calculator_backend.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 全局异常处理器
 * @author: hdr
 * @PACKAGE_NAME: com.example.calculator_backend.config
 * @DATE: 2025/8/11
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理参数验证异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> handleIllegalArgumentException(IllegalArgumentException e) {
        logger.warn("参数验证失败: {}", e.getMessage());
        return ResponseEntity.badRequest().body(createErrorResponse("参数错误", e.getMessage()));
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> handleNullPointerException(NullPointerException e) {
        logger.error("空指针异常", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(createErrorResponse("系统错误", "数据为空，请检查输入参数"));
    }

    /**
     * 处理数字格式异常
     */
    @ExceptionHandler(NumberFormatException.class)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> handleNumberFormatException(NumberFormatException e) {
        logger.warn("数字格式错误: {}", e.getMessage());
        return ResponseEntity.badRequest().body(createErrorResponse("格式错误", "请输入有效的数字"));
    }

    /**
     * 处理其他运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> handleRuntimeException(RuntimeException e) {
        logger.error("运行时异常", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(createErrorResponse("系统错误", "计算过程中发生错误，请稍后重试"));
    }

    /**
     * 处理所有其他异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> handleException(Exception e) {
        logger.error("未知异常", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(createErrorResponse("系统错误", "系统发生未知错误，请联系管理员"));
    }

    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String type, String message) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", true);
        error.put("type", type);
        error.put("message", message);
        error.put("timestamp", System.currentTimeMillis());
        return error;
    }
} 